<template>
  <section class="t-main service-apply-index">
    <div class="service-apply-warning ant-alert-warning">
      <span><i class="iconfont"> &#xe8df;</i></span>
      <div>
        按实际用量付费，使用前请详细阅读&nbsp;<span class="t-link t-cursor" @click="handlerAuthorization">服务介绍</span>
      </div>
    </div>
    <div class="topBar">
      <h2 class="title">{{ $route.query.type }}</h2>
      <div class="userDetail">
        <div class="itemMessage" v-for="(item, index) in currentList" :key="index">
          <div class="nameplate jee-bg-light">{{ item.name }}</div>
          <p class="amount">{{ item.value }}</p>
          <p class="buy" @click="" v-if="index != 1">去购买</p>
          <!-- v-if="isLogin && index != 1 && item.value !== 0"  v-if="index != 1"-->
          <p class="record jee-bg-color" v-if="index != 1" @click="toRecord()">
            购买记录
          </p>
        </div>
      </div>
    </div>
    <div class="auditMember" id="auditMember" style="margin-top: 12px;">
      <a-tabs v-model:activeKey="tabActive" @change="changeTopTabs" style="margin-bottom:16px">
        <a-tab-pane :key="item.key" :tab="item.tab" v-for="item in paneList"> </a-tab-pane>
      </a-tabs>
      <!-- 所属模块部分 -->
      <div class="searchContent" v-if="tabActive != 3">
        <div class="addTmp" v-if="tabActive == 1">
          <a-button class="addButton" type="primary"
          :disabled="!btnPerm.includes('addSignatureAble')"
           @click="addRecord">
            <template #icon>
              <span class="iconfont icon-Add iconadd"></span>
            </template>
            添加签名
          </a-button>
        </div>
        <div class="optionsAction">
          <div>
            <span class="flowScene_label">审核状态：</span>
            <a-select v-model:value="flowScene" style="width: 120px" :options="flowSceneStatus"
              :style="{ width: '112px' }" @select="">
            </a-select>
          </div>
          <div class="searchName">
            <a-input v-model:value="tmpName" placeholder="请输入模板名称" style="width: 192px">
              <template #suffix>
                <i class="iconfont icon-search"></i>
              </template>
            </a-input>
          </div>
          <div class="searchName" v-if="tabActive == 2">
            <a-input v-model:value="tmpContent" placeholder="请输入模板内容" style="width: 192px">
              <template #suffix>
                <i class="iconfont icon-search"></i>
              </template>
            </a-input>
          </div>
        </div>

      </div>
      <!-- 表格展示部分 -->
      <div :class="tabActive == 3 ? 'noleft' : ''">
        <baseTable :columns="columns.MSGservice['msg' + tabActive]" :dataSource="configData.records" :rowSelection="1"
          :scroll="scroll" :isShowPagination="isShowPagination" :total="configData.total" @changePage="changePage"
          :pageSize="pageSize">
          <template #bodyCell="{ column, text, record }">
            <template v-if="column.ellipsis">
              <table-tool-tip :text="text" :column="column"></table-tool-tip>
            </template>
            <template v-if="column.dataIndex === 'oparation' && tabActive == 1">
              <a :class="{ disable: !btnPerm.includes('defaultSetAble') }" @click="auditRecord(record.id)" class="settings">设置默认</a>
              <a-popconfirm :disabled="!btnPerm.includes('deleteAble')" placement="topRight" :ok-text="record.children && record.children.length ? '我知道了' : '确认'"
                cancel-text="取消" :showCancel="record.children && record.children.length ? false : true" @confirm="">
                <template #title>
                  <p style="width: 197px">
                    确定要删除该条签名?
                  </p>
                </template>
                <a :class="{ disable: !btnPerm.includes('deleteAble') }">删除</a>
              </a-popconfirm>
            </template>

            <template v-if="column.dataIndex === 'opDetail' && tabActive != 1">
              <a @click="auditRecord(record.id)">查看详情</a>
            </template>
          </template>
        </baseTable>
      </div>

    </div>
    <!-- 服务条例模态框 -->
    <base-modal :width="modAlProps.width" :isVisible="isVisible" :title="modAlProps.title"
      @handleCancle="isVisible = false" class="service" :isCancleBtn="null" v-if="isVisible">
      <template v-slot:body>
        <div>
          <h1 class="title">{{ modalTitle }}</h1>
          <div :v-html="serviceContent"></div>
        </div>
      </template>
    </base-modal>
    <!-- 添加模板模态框 -->
    <base-modal width="M" :isVisible="addAsignisVisible" :title="modAlProps.title" :buttons="buttons"
      :isCancleBtn="isCancleBtn" @handleOk="" @handleCancle="addAsignisVisible = false" v-if="addAsignisVisible"
      class="addAssgin">
      <template v-slot:body>
        <a-form name="advanced_search" class="ant-advanced-search-form" autoComplete="off" :model="formState"
          ref="workflowFrom" v-if="addAsignisVisible">
          <a-form-item :name="['flowName', 'value']" :label="formState.flowName.label" :rules="[formState.flowName.rule]">
            <a-input v-model:value="formState.flowName.value" :placeholder="formState.flowName.placeholder" show-count
              :maxlength="12" :minlength="2" allow-clear ref="flowName_ref" />
            <div class="tips"><span>请输入2~12个字符长度的签名，了解更多</span>
              <a type="text" class="button" @click="checkSignTem">签名/模板申请规范</a>
            </div>
          </a-form-item>

        </a-form>
      </template>
    </base-modal>
  </section>
</template>

<script lang="ts" setup>
import { ref, reactive, onBeforeMount, onMounted, nextTick } from "vue"
import { dataSourceType, detailDataItemType } from "@/type.d";
import baseModal from "@/components/modal/baseModal.vue";
import request from "@/api/index";
import baseTable from "@/components/table/baseTable.vue";
import columns from "@/components/table/tableConfig/tableColumn/systemTableColumn";
import { getTableScroll } from "@/components/table/tableConfig/table";
import { message } from "ant-design-vue";
import { useRouter } from "vue-router";
import {routerPerm} from '@/utils/common';
// form 验证
const checkrule_workFlowName = async (_rule: dataSourceType = {}, value: any) => {
  if (!value) {
    return Promise.reject(`${_rule.msg1}`);
  } else if (value.length > 12 || value.length < 2) {
    return Promise.reject(`${_rule.msg2}`);
  } else {
    return Promise.resolve();
  }
};
const router = useRouter();
// data
const btnPerm = ref<any[]>([]);
const currentList = ref<dataSourceType>([{
  name: '短信余量（条）',
  value: '0'
},
{
  name: '累计使用（条）',
  value: '0'
}]);
const isVisible = ref<boolean>(false);
const modAlProps: dataSourceType = reactive({
  width: "XL",
  title: "添加签名",
});
const serviceContent = ref('');
//data
const tabActive = ref(1);
const paneList = ref([
  {
    key: 1,
    tab: "待审核",
  },
  {
    key: 2,
    tab: "审核通过",
  },
  {
    key: 3,
    tab: "审核不通过",
  },
]);
//页面头部
const tmpName = ref<string>('');
const tmpContent = ref<string>('');
const flowSceneStatus = ref<dataSourceType['options']>([// 应用场景
  {
    value: '',
    label: '全部',
  },
  {
    value: '1',
    label: '审核不通过',
  },
  {
    value: '2',
    label: '审核通过',
  },
  {
    value: '3',
    label: '待审核',
  }
]);
const flowScene = ref('');
const selectOption = ref("");
// 添加模板模态框
const modalTitle = ref('JEECMS文本审核计费文档');
const addAsignisVisible = ref<Boolean>(false)
let isCancleBtn = ref<Boolean>(true);
let buttons = ref<dataSourceType[]>([{
  text: "保存",
  "html-type": "submit",
},]);

const formState = reactive<dataSourceType>({
  flowName: {
    value: "",
    rule: {
      required: true,
      validator: checkrule_workFlowName,
      trigger: ["blur"],
      msg1: '此项必填！',
      msg2: '长度为2-12！',
      api: "uniqueWorkFlowName",
      id: '',
      params: {}
    },
    label: "签名",
    placeholder: '请输入'
  },
});
//表格
let scroll: dataSourceType = reactive({ y: "", isFixed: false }); // 表单滚动设置
const configData = reactive({
  records: [],
  total: "",
});
const isShowPagination = ref(true);
// 当前页和数量
const pageCurrent = ref<number>(1);
const pageSize = ref<number>(10);
//methods
const handlerAuthorization = () => {
  isVisible.value = true;
  // fetchAppClientDocument();
}
const toRecord = () => { // 跳转到购买记录  
  router.push({
    path: "/system/smsService/buyHistory"
  });
}
const addRecord = () => { //点击添加签名
  console.log(addAsignisVisible.value, 'addAsignisVisible.value');
  addAsignisVisible.value = true;
}
const handleCancle = () => {
  addAsignisVisible.value = false;
  isVisible.value = false;
}
const checkSignTem = () => {
  isVisible.value = true;
}
const fetchAuthorizationsProduct = async () => {
  let res = await request.fetchAuthorizationsProduct({})
  // if (res.code === 200 || res.code === 1) {
  //   window.localStorage.setItem('version', res.data.version)
  //   window.localStorage.setItem('productAppId', res.data.productAppId)
  //   this.fetchApplyAuthorizations(res.data.productAppId)
  // }
}
// onMounted
onMounted(() => {
  btnPerm.value = routerPerm()
  getThreeMermberList({});
});
//methods
const changeTopTabs = () => {
  pageCurrent.value = 1;
  pageSize.value = 10;
  getThreeMermberList({});
};
const selectType = (item: dataSourceType) => {
  selectOption.value = item.value;
  pageCurrent.value = 1;
  pageSize.value = 10;
  getThreeMermberList({});
};
// 获取审核表格数据
const getThreeMermberList = async (datas: dataSourceType) => {
  const data: dataSourceType = {
    pageNumber: datas.pageNumber || pageCurrent.value,
    pageSize: datas.pageSize || pageSize.value,
    auditStatus: tabActive.value,
  };
  selectOption.value ? (data.moduleType = selectOption.value) : "";
  const telData = (await request.getThreeMermberList(data)) || {};
  let reqData = telData;
  configData.total = reqData.total;
  configData.records = reqData.records;
  configData.records.map(
    (item: dataSourceType, index: number) =>
      (item.key = item.id) && (item.index = index + 1)
  );
  nextTick(() => {
    let obj = getTableScroll(74, "auditMember", 240);
    scroll.y = obj.y;
    scroll.isFixed = obj.isFixed;
  });
};
//审核列表
const auditRecord = async (id: any) => {
  if(!btnPerm.value.includes('defaultSetAble')) return
};
//获取列表详情
const auditDetail = async (record: dataSourceType) => {
  let data = {
    logid: record.id,
  };
  let req = await request.getActionDetail(data);
};
//切换分页器
const changePage = (data: { pageCurrent: any; pageSize: any }) => {
  let datas: dataSourceType = {
    pageNumber: data.pageCurrent,
    pageSize: data.pageSize,
  };
  pageCurrent.value = data.pageCurrent;
  pageSize.value = data.pageSize;
  getThreeMermberList(datas);
};
//onbeforMount
onBeforeMount(() => {
  fetchAuthorizationsProduct();
})
</script>

<style lang="less" scoped>
.service-apply-index {
  padding: 16px;
  background: #fff;
  height: calc(100% - 72px);

  .searchContent {
    margin-left: auto;
    margin-right: 0px;
    display: flex;
    padding-bottom: 16px;
    justify-content: space-between;

    .optionsAction {
      flex: 1;
      display: flex;
      justify-content: end;
    }

    .flowScene_label {
      font-size: 14px;
      color: rgba(0, 0, 0, 0.85);
    }

    .searchName {
      font-size: 14px;
      color: #333;
      margin-left: 16px;
    }

    .icon-search {
      font-size: 20px;
      color: rgba(0, 0, 0, 0.45);
      position: absolute;
      right: 12px;
      top: 0px;
    }
  }

  .service-apply-warning {
    display: flex;
    align-items: center;
    padding: 8px 12px;
    font-size: 14px;

    .iconfont {
      margin-right: 8px;
      color: #faad14;
    }
  }

  .jee-bg-light {
    width: 4px;
    height: 18px;
    margin-right: 5px;
  }

  .topBar {
    overflow: hidden;
    border-radius: 4px;

    .title {
      color: #333333;
      font-size: 16px;
      margin-bottom: 18px;
      margin-top: 20px;
      font-weight: 600;
    }

    .userDetail {
      display: flex;
      flex-wrap: wrap;
    }

    .itemMessage {
      min-width: 226px;
      height: 107px;
      background-color: #eafafc;
      margin-right: 20px;
      padding: 16px 0 0 0;
      box-sizing: border-box;
      border-radius: 4px;
    }

    .itemMessage:hover {
      background-color: #d2f4f9;
    }

    .nameplate {
      width: 145px;
      height: 28px;
      border-radius: 0px 14px 14px 0px;
      color: #ffffff;
      font-size: 14px;
      text-align: center;
      line-height: 28px;
      background: #1ec6df;
    }

    .amount {
      color: #333333;
      font-size: 36px;
      padding: 8px 10px 0 22px;
      line-height: 1;
      display: inline-block;
    }

    .buy {
      display: inline-block;
      font-size: 14px;
      color: #ff6000;
      cursor: pointer;
      padding-right: 20px;
    }

    .record {
      display: inline-block;
      font-size: 14px;
      cursor: pointer;
      padding-right: 30px;
    }
  }

  .t-link {
    color: #1ec6df;
    text-decoration: underline;
    cursor: pointer;
  }

  .settings {
    margin-right: 12px;
  }


}
.disable {
  color: rgba(0, 0, 0, 0.25);
  cursor: not-allowed;
}
</style>
<style lang="less">
.service {
  .ant-modal-header {
    display: none;
  }

  .title {
    color: #333333;
    font-size: 16px;
    margin-bottom: 18px;
    margin-top: 20px;
    font-weight: 600;
    text-align: center;
  }
}
</style>
<style lang="less">
.noleft {
  .ant-table-thead .ant-table-cell:nth-last-of-type(1) {
    text-align: left;
  }
}

.service {
  z-index: 2000;
}

.addAssgin {
  z-index: 1900;

  .ant-form-item {
    margin-bottom: 0px;

    .tips {
      margin-top: 8px;
    }
  }
}
</style>
